<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0 text-dark">角色管理</h1>
            </div><!-- /.col -->
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a th:href="@{admin}">首页</a></li>
                    <li class="breadcrumb-item active">权限管理</li>
                    <li class="breadcrumb-item active">角色管理</li>
                </ol>
            </div><!-- /.col -->
        </div><!-- /.row -->
    </div><!-- /.container-fluid -->
</div>
<!-- Main content -->
<section class="content">
    <div class="card card-info">
        <shiro:hasPermission name="role:list">
            <form id="searchForm" class="needs-validation form-inline" novalidate="">
                <div class="form-group">
                    <label for="roleName">角色名称:</label>
                    <input type="text" class="form-control m-2" id="roleName">
                </div>
                <div class="form-group">
                    <button class="btn btn-primary ml-3" type="submit">查询</button>
                    <button class="btn btn-default ml-2" type="reset">重置</button>
                </div>
            </form>
        </shiro:hasPermission>
    </div>
    <div class="card card-body">
        <div id="toolbar" class="btn-group">
            <shiro:hasPermission name="role:add">
                <button id="btn_add" type="button" class="btn btn-primary">
                    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
                </button>
            </shiro:hasPermission>
            <shiro:hasPermission name="role:batchDelete">
                <button id="btn_batch_delete" type="button" class="btn btn-danger">
                    <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>批量删除
                </button>
            </shiro:hasPermission>
        </div>
        <table class="table-sm" id="table"></table>
    </div>
</section>


<!-- 表单模态框 -->
<section id="formModalWrapper">
    <div class="modal fade" id="formModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="formTitle"></h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div id="formContent"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveOrUpdateBtn">保存
                    </button>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- 权限分配模态框 -->
<section id="assignPermissionModalWrapper">
    <div class="modal fade" id="assignPermissionModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="assignPermissionTitle">分配权限</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <ul id="permissionTree" class="ztree"></ul>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="assignPermissionSaveOrUpdateBtn">保存
                    </button>
                </div>
            </div>
        </div>
    </div>
</section>

<script>

    $(function () {

        var editFlag = Core.parseBool("[[${@perms.hasPerm('role:edit')}]]");
        var deleteFlag = Core.parseBool("[[${@perms.hasPerm('role:delete')}]]");
        var assignPermissionFlag = Core.parseBool("[[${@perms.hasPerm('role:assignPerms')}]]");

        window.operateEvents = {
            // 点击编辑
            'click .btn_edit': function (e, value, row, index) {
                editRow(row.roleId)
            },
            // 点击分配角色
            'click .btn_assign': function (e, value, row, index) {
                assignPermission(row.roleId)
            },
            // 点击删除
            'click .btn_del': function (e, value, row, index) {
                deleteRow(row.roleId)
            }
        }
        var columns = [
            {checkbox: true},
            {
                field: 'name',
                title: '角色名称',
                align: "center"
            }, {
                field: 'description',
                title: '角色描述',
                align: "center"
            },
            {
                field: 'createTime',
                title: '创建时间',
                align: "center"
            },
            {
                field: 'operation',
                title: '操作',
                align: "center",
                width: 200,
                events: operateEvents,
                formatter: operationFormatter
            }];

        function operationFormatter(value, row, index) {
            var edit = editFlag ? '<button class="btn btn-info btn-sm btn_edit">编辑</button>' : '';
            var assign = assignPermissionFlag ? '<button class="btn btn-info btn-sm ml-1 btn_assign">分配权限</button>' : '';
            var del = deleteFlag ? '<button class="btn btn-danger btn-sm ml-1 btn_del">删除</button>' : '';
            return edit + assign + del;
        }

        var options = {
            id: "#table",
            url: '/role/list',
            columns: columns,
            toolbar: '#toolbar',
            showRefresh: true,
            queryParams: queryParams
        }
        Core.initTable(options);

        function refreshTable() {
            Core.refreshTable("#table")
        }

        // 查询参数
        function queryParams(params) {
            return {
                pageNumber: params.pageNumber,
                pageSize: params.pageSize,
                name: $("#roleName").val(),
            };
        }

        // 查询
        $('#searchForm').submit(function (event) {
            event.preventDefault();
            event.stopPropagation();
            refreshTable();
        })

        // 新增
        $('#btn_add').on('click', function () {
            Core.load("#formContent", "/role/add", function () {
                $('#formTitle').text('新增')
                $("#formModal").modal('show');
            }, 2);
        })

        // 编辑
        function editRow(id) {
            Core.load("#formContent", "/role/edit?roleId=" + id, function () {
                $('#formTitle').text('编辑')
                $("#formModal").modal('show');
            }, 2);
        }

        // 删除
        function deleteRow(roleId) {
            Core.confirm("确定删除？", function () {
                Core.postAjax("/role/delete", {"roleId": roleId}, function (data) {
                    if (data.status === 200) {
                        refreshTable();
                    }
                    layer.msg(data.msg);
                })
            })
        }

        // 批量删除
        $("#btn_batch_delete").on('click', function () {
            var checkedRows = Core.selectMutiData("#table");
            if (checkedRows) {
                Core.confirm("确定删除选中的" + checkedRows.length + "条记录？", function () {
                    var ids = [];
                    $.each(checkedRows, function (i, item) {
                        ids.push(item.roleId);
                    })
                    Core.postAjax("/role/batch/delete", {"ids": ids}, function (data) {
                        if (data.status === 200) {
                            refreshTable();
                        }
                        layer.msg(data.msg);
                    })
                })
            }
        })

        // 保存或更新
        $('#saveOrUpdateBtn').on('click', function () {
            var $f = $('#userForm');
            var valid = $f[0].checkValidity();
            var url = $f.find("input[name='roleId']").val() ? "/role/edit" : "/role/add"
            if (valid) {
                Core.mask("#saveOrUpdateBtn");
                Core.postAjax(url, $f.serialize(), function (data) {
                    Core.unmask("#saveOrUpdateBtn");
                    if (data.status === 200) {
                        $("#formModal").modal("hide");
                        refreshTable();
                    }
                    layer.msg(data.msg);
                }, function () {
                    Core.unmask("#saveOrUpdateBtn");
                })
            }
            $f.addClass("was-validated")
        })

        var selectRoleIds;
        var roleIdChecked;
        var loadRoleCount = 0;

        //树-初始化设置
        var treeSetting = {
            check: {
                enable: true,
                chkStyle: "checkbox",
                chkboxType: {"Y": "ps", "N": "s"}
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "parentId"
                }
            }
        };

        // 分配权限
        function assignPermission(roleId) {
            roleIdChecked = roleId;
            Core.postAjax("/role/assign/permission/list", {"roleId": roleId}, function (data) {
                var zNodes = data;
                $.fn.zTree.init($("#permissionTree"), treeSetting, zNodes);
                $("#assignPermissionModal").modal("show");
            })
        }

        function handleRoleData(res) {
            selectRoleIds = res.hasRoles;
            return res.rows;
        }

        $('#assignPermissionSaveOrUpdateBtn').on('click', function () {
            Core.mask("#assignPermissionSaveOrUpdateBtn")
            var permissionIdStr = "";
            var treeObj = $.fn.zTree.getZTreeObj("permissionTree");
            var nodes = treeObj.getCheckedNodes(true);
            for (var i = 0; i < nodes.length; i++) {
                if (i === (nodes.length - 1)) {
                    permissionIdStr += nodes[i].permissionId;
                } else {
                    permissionIdStr += nodes[i].permissionId + ",";
                }
            }
            Core.postAjax('/role/assign/permission', {
                roleId: roleIdChecked,
                permissionIdStr: permissionIdStr
            }, function (data) {
                Core.unmask("#assignPermissionSaveOrUpdateBtn");
                if (data.status === 200) {
                    $("#assignPermissionModal").modal("hide");
                }
                layer.msg(data.msg);
            }, function (xhr) {
                Core.unmask("#assignPermissionSaveOrUpdateBtn");
                console.log(xhr)
                layer.msg('保存失败')
            });
        })

    });

</script>